package com.haixiaoke.saas.department.service.impl;

import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.config.sms.SmsConfig;
import com.haixiaoke.saas.common.constant.HouseConstants;
import com.haixiaoke.saas.common.constant.TenantConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.exception.ServiceException;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.common.utils.sms.SmsUtils;
import com.haixiaoke.saas.contract.fadada.service.FaDaDaService;
import com.haixiaoke.saas.department.domain.ElectronicVisa;
import com.haixiaoke.saas.department.domain.ElectronicVisaRecord;
import com.haixiaoke.saas.department.domain.Tenant;
import com.haixiaoke.saas.department.mapper.ElectronicVisaMapper;
import com.haixiaoke.saas.department.service.IElectronicVisaRecordService;
import com.haixiaoke.saas.department.service.IElectronicVisaService;
import com.haixiaoke.saas.department.service.ITenantService;
import com.haixiaoke.saas.house.domain.House;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 企业电子签信息Service业务层处理
 *
 * @author panda
 * @date 2024-05-29
 */
@Service
public class ElectronicVisaServiceImpl implements IElectronicVisaService {
    @Autowired
    private ElectronicVisaMapper electronicVisaMapper;
    @Autowired
    private IElectronicVisaRecordService electronicVisaRecordService;
    @Autowired
    private ITenantService tenantService;
    @Autowired
    private FaDaDaService faDaDaService;
    @Autowired
    private SmsUtils smsUtils;
    @Autowired
    private SmsConfig smsConfig;

    /**
     * 查询企业电子签信息
     *
     * @param visaId 企业电子签信息主键
     * @return 企业电子签信息
     */
    @Override
    public ElectronicVisa selectElectronicVisaByVisaId(Long visaId) {
        return electronicVisaMapper.selectElectronicVisaByVisaId(visaId);
    }

    /**
     * 查询企业电子签信息列表
     *
     * @param electronicVisa 企业电子签信息
     * @return 企业电子签信息
     */
    @Override
    public List<ElectronicVisa> selectElectronicVisaList(ElectronicVisa electronicVisa) {
        return electronicVisaMapper.selectElectronicVisaList(electronicVisa);
    }

    /**
     * 新增企业电子签信息
     *
     * @param electronicVisa 企业电子签信息
     * @return 结果
     */
    @Override
    public int insertElectronicVisa(ElectronicVisa electronicVisa) {
        electronicVisa.setCreateTime(DateUtils.getNowDate());
        return electronicVisaMapper.insertElectronicVisa(electronicVisa);
    }

    /**
     * 修改企业电子签信息
     *
     * @param electronicVisa 企业电子签信息
     * @return 结果
     */
    @Override
    public int updateElectronicVisa(ElectronicVisa electronicVisa) {
        electronicVisa.setUpdateTime(DateUtils.getNowDate());
        return electronicVisaMapper.updateElectronicVisa(electronicVisa);
    }

    /**
     * 批量删除企业电子签信息
     *
     * @param visaIds 需要删除的企业电子签信息主键
     * @return 结果
     */
    @Override
    public int deleteElectronicVisaByVisaIds(Long[] visaIds) {
        return electronicVisaMapper.deleteElectronicVisaByVisaIds(visaIds);
    }

    /**
     * 删除企业电子签信息信息
     *
     * @param visaId 企业电子签信息主键
     * @return 结果
     */
    @Override
    public int deleteElectronicVisaByVisaId(Long visaId) {
        return electronicVisaMapper.deleteElectronicVisaByVisaId(visaId);
    }

    @Override
    @Transactional
    public int addVisaContractNumber(ElectronicVisaRecord record) {
        int result;
        ElectronicVisa visa;
        if (ObjectUtil.isNull(record.getVisaId())) {
            ElectronicVisa electronicVisa = electronicVisaMapper.selectElectronicVisaByTenantId(record.getTenantId());
            if (ObjectUtil.isNotEmpty(electronicVisa)) {
                throw new ServiceException("数据异常");
            }
            visa = new ElectronicVisa();
            visa.setContractTotalNumber(record.getVisaNum());
            visa.setCreateTime(DateUtils.getNowDate());
            visa.setTenantId(record.getTenantId());
            result = electronicVisaMapper.insertElectronicVisa(visa);
        } else {
            visa = electronicVisaMapper.selectElectronicVisaByVisaId(record.getVisaId());
            visa.setContractTotalNumber(visa.getContractTotalNumber() + record.getVisaNum());
            result = electronicVisaMapper.updateElectronicVisa(visa);
        }
        if (result > 0) {
            record.setVisaRecordType(TenantConstants.VISA_RECORD_TYPE_ADD);
            record.setCreateTime(DateUtils.getNowDate());
            record.setVisaId(visa.getVisaId());
            electronicVisaRecordService.insertElectronicVisaRecord(record);
        }
        return result;
    }

    @Override
    public int addVisaContractNumber(Long visaId) {
        return electronicVisaMapper.addVisaContractNumber(visaId);
    }

    @Override
    @Transactional
    public int subtractVisaContractNumber(ElectronicVisaRecord record) {
        int result;
        ElectronicVisa visa = null;
        if (ObjectUtil.isNull(record.getVisaId())) {
            throw new ServiceException("电子签总量已为0，无法减少");
        } else {
            visa = electronicVisaMapper.selectElectronicVisaByVisaId(record.getVisaId());
            if (visa.getContractTotalNumber() - record.getVisaNum() < 0) {
                throw new ServiceException("电子签总量不足，无法减少");
            }
            visa.setContractTotalNumber(visa.getContractTotalNumber() - record.getVisaNum());
            result = electronicVisaMapper.updateElectronicVisa(visa);
        }
        if (result > 0) {
            record.setVisaRecordType(TenantConstants.VISA_RECORD_TYPE_SUBTRACT);
            record.setCreateTime(DateUtils.getNowDate());
            record.setVisaId(visa.getVisaId());
            electronicVisaRecordService.insertElectronicVisaRecord(record);
        }
        return result;
    }

    @Override
    public int subtractVisaContractNumber(Long visaId) {
        return electronicVisaMapper.subtractVisaContractNumber(visaId);
    }

    @Override
    public ElectronicVisa selectElectronicVisaByTenantId(String tenantId) {
        return electronicVisaMapper.selectElectronicVisaByTenantId(tenantId);
    }

    @Override
    public ElectronicVisa selectElectronicVisaByCooperationType(House house) {
        ElectronicVisa electronicVisa = null;
        if (HouseConstants.COOPERATION_TYPE_HOUSE_RENTAL.equals(house.getCooperationType())) {
            //电子合同
            Tenant tenant = tenantService.selectDepByDepId(house.getTenantId());
            if (TenantConstants.ELECTRONIC_VISA_STATUS_UN_OPEN.equals(tenant.getElectronicVisaStatus())) {
                throw new ServiceException("电子合同未开通,请去管理端开通电子合同");
            }
            //房屋委托
            electronicVisa = this.selectElectronicVisaByTenantId(house.getTenantId());
        } else if (HouseConstants.COOPERATION_TYPE_AGENCY_SERVICE.equals(house.getCooperationType())) {
            //代理服务
            electronicVisa = this.selectElectronicVisaByProprietorUserId(house.getProprietorUserId());
        }
        return electronicVisa;
    }

    /**
     * 根据业主id查询企业电子签信息
     *
     * @param proprietorId
     * @return
     */
    @Override
    public ElectronicVisa selectElectronicVisaByProprietorUserId(Long proprietorId) {
        return electronicVisaMapper.selectElectronicVisaByProprietorUserId(proprietorId);
    }

    @Override
    public AjaxResult sendSmsAuth(String tenantId) {
        Tenant tenant = tenantService.selectDepByDepId(tenantId);
        if (StrUtil.equals(TenantConstants.ELECTRONIC_VISA_STATUS_OPEN, tenant.getElectronicVisaStatus())) {
            return AjaxResult.error("电子签已开通,请勿重复操作");
        }
        if (StrUtil.isBlank(tenant.getContactsPhone())) {
            return AjaxResult.error("企业的联系方式不能为空");
        }
        ElectronicVisa electronicVisa = electronicVisaMapper.selectElectronicVisaByTenantId(tenantId);
        if (ObjectUtil.isEmpty(electronicVisa)) {
            electronicVisa = new ElectronicVisa();
            electronicVisa.setCreateTime(DateUtils.getNowDate());
            electronicVisa.setTenantId(tenantId);
            electronicVisa.setElectronicVisaType(TenantConstants.ELECTRONIC_VISA_TYPE_ENTERPRISE);
            electronicVisaMapper.insertElectronicVisa(electronicVisa);
        }
        if (ObjectUtil.isNull(electronicVisa.getVisaId())) {
            return AjaxResult.error("电子签数据操作失败");
        }
        String corpAuthUrl = faDaDaService.getCorpAuthUrl(String.valueOf(electronicVisa.getVisaId()), tenant.getContactsPhone());
        boolean result = smsUtils.sendTemplateSmsWithData(tenant.getContactsPhone(), smsConfig.getFadadaAuthInformTemplateCode(), new String[]{corpAuthUrl});
        if (result) {
            return AjaxResult.success("短信发送成功,请尽快授权");
        }
        return AjaxResult.error("短信发送失败,请联系管理员");
    }

}
